/**
 * 项目名：化工企业安全生产信息化管理平台
 * 日期：    2020-03-01 23:13:59
 * Copyright (c) 2015- -版权所有
 */

package com.joysuch.wwyt.edu.controller;

import cn.zlg.common.springmvc.validate.constraints.NotNull;
import cn.zlg.common.util.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.core.bean.SimpleSelectListBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.service.SimpleSelectListService;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.edu.bean.*;
import com.joysuch.wwyt.edu.bean.EduDoExamResultBean.ExamResult;
import com.joysuch.wwyt.edu.bean.EduExamCenterListBean.AppSearchEduExamRecord;
import com.joysuch.wwyt.edu.bean.EduExamCenterListBean.SearchEduExamCenter;
import com.joysuch.wwyt.edu.bean.EduExamListBean.SearchEduExam;
import com.joysuch.wwyt.edu.entity.EduExam;
import com.joysuch.wwyt.edu.service.EduExamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.util.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/edu/exam")
@Api(tags = "/edu/exam 教育考试")
public class EduExamController {

    private static final Logger logger = LoggerFactory.getLogger(EduExamController.class);

    @Autowired
    private EduExamService eduExamService;
    @Autowired
    private SimpleSelectListService simpleSelectListService;

    @RequiresPermissions("edu:exam:add")
    @RequestMapping("add")
    public Object add(@Valid @RequestBody EduExamEditBean entity) {
        eduExamService.add(entity);
        return ResultBean.success("");
    }

    @RequiresPermissions("edu:exam:update")
    @RequestMapping("update")
    public Object update(@Valid @RequestBody EduExamEditBean entity) {
        if (entity.getId() == null) {
            return ResultBean.fail(102, "未指定主键");
        }
        eduExamService.update(entity);
        return ResultBean.success("");
    }

    // @RequiresPermissions("edu:exam")
    @RequestMapping("page")
    public Object page(Pageable page, SearchEduExam condition) {
        page = PageDataUtils.addOrderByDesc(page, "id");
        Page<EduExamListBean> data = eduExamService.findByPage(page, condition);
        return ResultBean.pageData(data.getContent(), data.getTotalElements());
    }

    // @RequiresPermissions("edu:exam")
    @RequestMapping("select-page")
    public Object selectPage(Pageable page, SearchEduExam condition) {
        page = PageDataUtils.addOrderByDesc(page, "id");
        Page<EduExamListBean> data = eduExamService.findByPage(page, condition);
        return ResultBean.pageData(data.getContent(), data.getTotalElements());
    }

    @ApiOperation("查询没有被培训关联的考试")
    @GetMapping("selectNoTrainningExam")
    public Object selectNoTrainningExam(SearchEduExam condition) {
        return eduExamService.selectNoTrainningExam(condition);
    }

    @RequestMapping("simple-list")
    public Object simpleList() {
        List<SimpleSelectListBean> data = simpleSelectListService.list(EduExam.class, "name");
        return ResultBean.success(data);
    }


    @RequestMapping("check-course-learn")
    public Object checkCourseLearn(Long examId) {
        return ResultBean.success(eduExamService.checkCourseLearn(Context.getCurrentUserId(), examId));
    }

    @RequiresPermissions("edu:exam:delete")
    @RequestMapping("delete")
    public Object delete(Long id) throws Exception {
        eduExamService.delete(id);
        return ResultBean.success("");
    }

    @RequestMapping("publish")
    public Object publish(Long id, @RequestParam(defaultValue = "1") Integer state) throws Exception {
        Assert.notNull(id, "id不能为空");
        Assert.isTrue(state == 1 || state == 0, "状态只能为0、1");
        eduExamService.changeState(id, state);
        return ResultBean.success("");
    }

    // @RequiresPermissions("edu:exam")
    @RequestMapping("get")
    public Object getById(@Valid @NotNull(field = "id") Long id,@RequestParam(required = false,defaultValue = "false")Boolean isWeb) {
        return ResultBean.success(eduExamService.getById(id,isWeb));
    }

    @RequestMapping("exam-center")
    @ApiOperation("考试中心-分页查询")
    public Object exampCenter(Pageable page, SearchEduExamCenter condition) {
        page = PageDataUtils.addOrderByDesc(page, "updateTime");
        Page<EduExamCenterListBean> data = eduExamService.queryUserExamCenterPage(page, Context.getCurrentUserId(),
                condition);
        return ResultBean.pageData(data);
    }


    @RequestMapping("marking-papers-center")
    @ApiOperation("阅卷中心-分页查询")
    public Object markingPapersCenter(Pageable page, EduMarkingPapersCenterListBean.SearchEduMarkingPapersCenter condition) {
        return eduExamService.queryUserMarkingPapersCenterPage(page, Context.getCurrentUserId(),
                condition);
    }

    /**
     * 查询个人考试记录，APP端用
     *
     * @param page
     * @param condition
     * @return
     */
    @RequestMapping("personal-exam-record")
    public Object personalExamRecord(Pageable page, AppSearchEduExamRecord condition) {
        Page<EduExamCenterListBean> data = eduExamService.queryUserExamRecordPage(page, Context.getCurrentUserId(),
                condition);
        return ResultBean.pageData(data);
    }

    @RequestMapping("start")
    @ApiOperation("开始考试")
    public Object startDoExam(@Valid @NotNull(field = "id") Long id) {
        long startTime = System.currentTimeMillis();
        logger.info("考试开始执行：{}",startTime);
        EduDoExamBean exam = eduExamService.loadExam(id, Context.getCurrentUserId());
        logger.info("考试接口执行结束耗时:{}",System.currentTimeMillis()-startTime);
        return ResultBean.success(exam);
    }


    @RequestMapping("cache/answers")
    @ApiOperation("缓存答案")
    public Object cacheAnswers(@RequestBody EduDoExamResultBean result) {
        eduExamService.cacheAnswers(result, Context.getCurrentUserId(), 1);
        return ResultBean.defaultSuccessResult();
    }

    @RequestMapping("get/cache/answers")
    @ApiOperation("获取缓存答案")
    public Object getCacheAnswers(@RequestParam("examId") Long examId) {
        EduDoExamResultBean bean = new EduDoExamResultBean();
        bean.setId(examId);
        String json = eduExamService.cacheAnswers(bean, Context.getCurrentUserId(), 3);
        return ResultBean.success(json);
    }


    @RequestMapping("submit")
    @ApiOperation("提交试卷")
    public Object submitExam(@RequestBody EduDoExamResultBean result) {
        ExamResult exam = eduExamService.submit(result, Context.getCurrentUserId(), 0);
        return ResultBean.success(exam);
    }

    @RequestMapping("submit-marking-papers")
    @ApiOperation("阅卷提交")
    public Object submitMarkingPapers(@RequestBody List<EduDoExamResultBean.ExamUserAnswer> examUserAnswerList) {
        eduExamService.submitMarkingPapers(examUserAnswerList);
        return ResultBean.success("");
    }

    @RequestMapping("user-exam-record")
    public Object queryUserExamRecord(Long examId, String userIds) {
        Assert.notNull(examId, "考试ID不能为空");
        Assert.hasLength(userIds, "用户列表不能为空");
        List<Long> idList = CollectionUtils.splitAndConvert(userIds, ",", Long::parseLong);
        EduExamUserRecordBean exam = eduExamService.queryExamUserRecords(examId, idList);
        return ResultBean.success(exam);
    }

    @ApiOperation(value = "app我的考试中心-全部")
    @GetMapping("myExamList")
    public Object myExamList(EduTrainningRecordListBean.SearchEduTrainningRecord condition) {
        return eduExamService.myExamList(condition);
    }

    @RequestMapping("question-list")
    public Object queryQuestionList(Long id, Integer showAnswer, Long userId, Long examRecordId) {
        // 当传入showAnswer=1时，不论考试设置中是否设置过隐藏答案，答案都将显示
        //app端未传userId,取登录的用户id
        if (userId == null || userId == 0) {
            userId = Context.getCurrentUserId();
        }
        List<EduTestPaperQuestionDetailBean> list = eduExamService.queryQuestionListByExamId(id, showAnswer, userId, examRecordId);
        return ResultBean.success(list);
    }

    @RequestMapping("marking-papers")
    public Object queryMarkingPapersList(Long examId, Long userId, Long examRecordId, String questionType, Integer isScore) {
        //app端未传userId,取登录的用户id
        if (userId == null || userId == 0) {
            userId = Context.getCurrentUserId();
        }
        List<EduTestPaperQuestionDetailBean> list = eduExamService.queryMarkingPapersList(examId, userId, examRecordId, questionType, isScore);
        return ResultBean.success(list);
    }

    @GetMapping("exam-excel")
    @ApiOperation("考试管理成绩导出")
    public void examExcel(Long examId, HttpServletRequest request, HttpServletResponse response) {
        eduExamService.examExcel(examId, request, response);
    }

    @RequestMapping("import-exam")
    @ApiOperation("考试管理成绩导入")
    public Map<String, Object> importExcel(Long examId, @RequestParam("file") MultipartFile file) {
         Map<String, Object> map = new HashMap<>();
        try {
            map = eduExamService.importExcel(examId,file);
        }catch (Exception e){
            map.put("status",-1);
            map.put("data", "导入异常");
            logger.error(e.getMessage(),e);
        }

        return map;
    }
    @GetMapping("initialized-data")
    @ApiOperation(" 考试管理老数据处理")
    public Object initializedData(){
       eduExamService.initializedData();
       return ResultBean.success("");
    }

    @RequestMapping("getPaper")
    public Object getPaper(@Valid @NotNull(field = "id") Long id) {
        return ResultBean.success(eduExamService.getPaper(id));
    }
}
